//
//  XMTopicView.m
//  XMJJ_zml
//
//  Created by 丁浩 on 2025/6/5.
//

#import "XMTopicView.h"
#import "XMNetwork+publish.h"
#import "XMTopicModel.h"

@interface XMTopicView ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>

@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UITextField *topicTextField;
@property (nonatomic, strong) UITableView *tbl;

@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, strong) NSMutableArray *topicArr;

@end

@implementation XMTopicView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self creatUI];
    }
    return self;
}

- (void)creatUI {
    self.backgroundColor = kColorHEXA(0x464646, 0.46);
    [self addSubview:self.contentView];
    [_contentView addSubview:self.topicTextField];
    [_contentView addSubview:self.tbl];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(KScaleWidth(18.0), _tbl.y - KScaleWidth(43.0), KScaleWidth(53.0), KScaleWidth(27.0)) font:KFontSize(12.0) textColor:kColorHEX(0x333333) textAlignment:NSTextAlignmentCenter];
    titleLabel.backgroundColor = kColorHEX(0xF5F5F5);
    [titleLabel setCornerRadius:titleLabel.height/2];
    titleLabel.text = @"#话题";
    [_contentView addSubview:titleLabel];
    _contentView.y = self.height;
    self.alpha = 0;
}

- (void)showWithTopic:(NSString *)topicStr {
    XMWeakSelf;
    [UIView animateWithDuration:.3 animations:^{
        weakSelf.alpha = 1;
        weakSelf.contentView.y = weakSelf.height - weakSelf.contentView.height;
        weakSelf.topicTextField.text = [NSString stringWithFormat:@"#%@", topicStr];
    } completion:^(BOOL finished) {
        [weakSelf.topicTextField becomeFirstResponder];
        if (topicStr.length > 0) {
            [weakSelf.topicTextField selectAll:self];
        }
    }];
    [self getRecommendTopic:self.topicTextField.text];
}

- (void)disMiss {
    XMWeakSelf;
    [UIView animateWithDuration:.3 animations:^{
        weakSelf.alpha = 0;
        weakSelf.contentView.y = weakSelf.height;
    } completion:^(BOOL finished) {
        [weakSelf removeFromSuperview];
    }];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    self.topicSelectBlock ? self.topicSelectBlock(_topicTextField.text) : nil;
    [self disMiss];
    return YES;
}

- (void)getRecommendTopic:(NSString *)content {
    XMWeakSelf;
    [_Network getRecommendTopicWithContent:content
                                    success:^(id  _Nonnull responseObject) {
        NSArray *topicModelArr = [NSArray yy_modelArrayWithClass:[XMTopicModel class] json:[responseObject safeArrayForKey:@"data"]];
        if (weakSelf.topicArr.count > 0) {
            [weakSelf.topicArr removeAllObjects];
        }
        XMTopicModel *topicModel = [[XMTopicModel alloc] init];
        topicModel.name = content;
        [self.topicArr addObject:topicModel];
        [weakSelf.topicArr addObjectsFromArray:topicModelArr];
        [weakSelf.tbl reloadData];
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

#pragma mark - Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.topicArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return KScaleWidth(56.0);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellName = @"XMTopicCellName";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellName];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellName];
        cell.textLabel.font = KFontSize(16.0);
        cell.textLabel.textColor = kColorHEX(0x333333);
    }
    XMTopicModel *topicModel = self.topicArr[indexPath.row];
    cell.textLabel.text = topicModel.name;//@"#见一面";
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    XMTopicModel *topicModel = self.topicArr[indexPath.row];
    if ([topicModel.name containsString:@"删除"]) {
        self.topicSelectBlock ? self.topicSelectBlock(@"") : nil;
    }
    else {
        self.topicSelectBlock ? self.topicSelectBlock(topicModel.name) : nil;
    }
    [self disMiss];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self endEditing:YES];
}

- (void)inputChangedAction:(UITextField *)textField {
    if (textField.text.length > 0) {
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1*NSEC_PER_SEC), dispatch_get_main_queue(), ^{
            
//        });
        if (_timer) {
            [_timer invalidate];
        }
        XMWeakSelf;
        _timer = [NSTimer scheduledTimerWithTimeInterval:1 repeats:NO block:^(NSTimer * _Nonnull timer) {
            [weakSelf getRecommendTopic:textField.text];
        }];
//        [self getRecommendTopic:textField.text];
    }
    else {
        [self.topicArr removeAllObjects];
        XMTopicModel *topicModel = [[XMTopicModel alloc] init];
        topicModel.name = @"删除标签";
        [self.topicArr addObject:topicModel];
        [_tbl reloadData];
    }
}

#pragma mark - Init
- (UIView *)contentView {
    if (!_contentView) {
        _contentView = [[UIView alloc] initWithFrame:CGRectMake(0, kNavagationBarH + KScaleWidth(30.0), self.width, self.height - kNavagationBarH - KScaleWidth(30.0))];
        _contentView.backgroundColor = kColorHEX(0xffffff);
        [_contentView setPartCornerWithRectCorner:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadius:KScaleWidth(12.0)];
    }
    return _contentView;
}

- (UITextField *)topicTextField {
    if (!_topicTextField) {
        _topicTextField = [[UITextField alloc] initWithFrame:CGRectMake(KScaleWidth(14.0), KScaleWidth(14.0), self.width - KScaleWidth(14.0)*2, KScaleWidth(24.0))];
        _topicTextField.font = KFontSize(15.0);
        _topicTextField.textColor = kColorHEX(0x333333);
        _topicTextField.returnKeyType = UIReturnKeyDone;
        _topicTextField.delegate = self;
        [_topicTextField addTarget:self action:@selector(inputChangedAction:) forControlEvents:UIControlEventEditingChanged];
    }
    return _topicTextField;
}

- (UITableView *)tbl {
    if (!_tbl) {
        _tbl = [[UITableView alloc] initWithFrame:CGRectMake(0, KScaleWidth(200.0), self.width, self.contentView.height - KScaleWidth(200.0))];
        _tbl.delegate = self;
        _tbl.dataSource = self;
        _tbl.separatorColor = kColorHEX(0xF1F1F1);
        _tbl.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
        if (@available(iOS 15.0, *)) {
            _tbl.sectionHeaderTopPadding = 0;
        } else {
            _tbl.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            // Fallback on earlier versions
        }
    }
    return _tbl;
}

- (NSMutableArray *)topicArr {
    if (!_topicArr) {
        _topicArr = [NSMutableArray array];
    }
    return _topicArr;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
